package com.example.restatr.Atcivity.Movie;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.Movie.Bean.MovieCommentBean;
import com.example.restatr.Atcivity.Movie.Bean.MovieFilmBean;
import com.example.restatr.Atcivity.Movie.Bean.MovieTheatreTimesBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MovieInfoAt extends AppCompatActivity {
    private MovieFilmBean.RowsBean 电影信息;
    private ImageView head;
    private TextView name;
    private TextView score;
    private TextView overLike;
    private TextView playDate;
    private ImageView likeImg;
    private WebView web;
    private int isLike = 0;
    private RecyclerView movieComment;
    private List<MovieCommentBean.RowsBean> CommentRowsBeans = new ArrayList<>();
    private LinearLayout Null;
    private CardView btn;
    private RelativeLayout pl;
    private EditText plEdText;
    private MaterialButton button;
    private float ratingScore;
    private MovieTheatreTimesBean.RowsBean 影院影片场次信息;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_info_at);
        电影信息 = new Gson().fromJson(getIntent().getStringExtra("电影信息"), new TypeToken<MovieFilmBean.RowsBean>() {
        }.getType());
        head = findViewById(R.id.head);
        name = findViewById(R.id.name);
        score = findViewById(R.id.score);
        overLike = findViewById(R.id.overLike);
        web = findViewById(R.id.web);
        likeImg = findViewById(R.id.likeImg);
        movieComment = findViewById(R.id.movieComment);
        playDate = findViewById(R.id.playDate);
        Null = findViewById(R.id.Null);
        btn = findViewById(R.id.btn);
        pl = findViewById(R.id.pl);
        plEdText = findViewById(R.id.pl_edText);
        button = findViewById(R.id.button);

        Glide.with(this)
                .load(Tools.ip + 电影信息.getCover())
                .into(head);
        name.setText(电影信息.getName());
        score.setText(String.valueOf(电影信息.getScore()));
        overLike.setText(String.valueOf(电影信息.getFavoriteNum()));
        web.loadData(电影信息.getIntroduction(), "text/html", "UTF-8");
        playDate.setText(电影信息.getPlayDate());
        String intent = getIntent().getStringExtra("Intent");
        if (intent != null && intent.equals("Comment")) {
            btn.setVisibility(View.GONE);
            pl.setVisibility(View.VISIBLE);
        }
        plEdText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (plEdText.getText().toString().length() > 0) {
                    button.setVisibility(View.VISIBLE);
                } else {
                    button.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        GetMovieComment();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.like:
                PostFilmLike();
                break;
            case R.id.btn:
                GetMovieTheatreTimes();
                break;
            case R.id.button:
                View inflate = getLayoutInflater().inflate(R.layout.wm_pj_dailog_layout, null);
                TextView text = inflate.findViewById(R.id.text);
                RatingBar rating = inflate.findViewById(R.id.rating);
                MaterialButton button = inflate.findViewById(R.id.button);
                AlertDialog.Builder builder = new AlertDialog.Builder(MovieInfoAt.this);
                builder.setView(inflate).create();
                final AlertDialog show = builder.show();
                text.setText("电影评分");
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ratingScore = rating.getRating();
                        show.dismiss();
                        posComment();
                    }
                });
                break;
        }
    }

    //发表评论
    private void posComment() {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("content", plEdText.getText().toString());
                jsonObject.put("movieId", 电影信息.getId());
                jsonObject.put("score", ratingScore);
                String post = Tools.Post("/prod-api/api/movie/film/comment", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JSONObject jx = new JSONObject(post);
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        pl.setVisibility(View.GONE);
                        GetMovieComment();
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //想看
    private void PostFilmLike() {
        if (isLike != 200) {
            new Thread(() -> {
                try {
                    String post = Tools.Post("/prod-api/api/movie/film/like/" + 电影信息.getId(),
                            MainActivity.sp.getString("token", ""), "");
                    JSONObject jx = new JSONObject(post);
                    String msg = jx.getString("msg");
                    isLike = jx.getInt("code");
                    runOnUiThread(() -> {
                        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                        if (isLike == 200) {
                            likeImg.setBackgroundResource(R.drawable.ic_baseline_favorite_24);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }

    //判断评分等级
    private void GetLevel(float score, TextView textView) {
        if (score >= 4) {
            textView.setText("非常满意");
        } else if (score >= 3 && score < 4) {
            textView.setText("满意");
        } else if (score >= 2 && score < 3) {
            textView.setText("差");
        } else if (score < 2) {
            textView.setText("非常差");
        }
    }

    //获取电影评论
    private void GetMovieComment() {
        CommentRowsBeans.clear();
        new Thread(() -> {
            String get = Tools.Get("/prod-api/api/movie/film/comment/list?movieId=" + 电影信息.getId(), "");
            MovieCommentBean movieCommentBean = new Gson().fromJson(get, MovieCommentBean.class);
            List<MovieCommentBean.RowsBean> collect = movieCommentBean.getRows().stream().sorted(Comparator.comparing(MovieCommentBean.RowsBean::getCommentDate).reversed()).collect(Collectors.toList());
            runOnUiThread(() -> {
                if (collect.size() > 0) {
                    CommentRowsBeans.addAll(collect);
                    movieComment.setAdapter(new PlListAdapter());
                } else {
                    movieComment.setVisibility(View.GONE);
                    Null.setVisibility(View.VISIBLE);
                }
            });
        }).start();
    }

    private void GetMovieTheatreTimes() {
        new Thread(() -> {
            String get = Tools.Get("/prod-api/api/movie/theatre/times/list?movieId=" + 电影信息.getId(), "");
            MovieTheatreTimesBean movieTheatreTimesBean = new Gson().fromJson(get, MovieTheatreTimesBean.class);
            影院影片场次信息 = movieTheatreTimesBean.getRows().get(0);
            runOnUiThread(() -> {
                Intent intent = new Intent(this, ChooseSeatAt.class);
                intent.putExtra("电影信息", new Gson().toJson(电影信息));
                intent.putExtra("影院影片场次信息", new Gson().toJson(影院影片场次信息));
                startActivity(intent);
            });
        }).start();
    }


    class PlListAdapter extends RecyclerView.Adapter<PlListAdapter.PlListViewHolder> {

        @NonNull
        @Override
        public PlListAdapter.PlListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(MovieInfoAt.this).inflate(R.layout.pj_list_item, parent, false);
            return new PlListAdapter.PlListViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull PlListAdapter.PlListViewHolder holder, int position) {
            holder.likeLL.setVisibility(View.VISIBLE);
            holder.name.setText(CommentRowsBeans.get(position).getNickName());
            holder.date.setText(CommentRowsBeans.get(position).getCommentDate());
            holder.score.setRating(CommentRowsBeans.get(position).getScore());
            GetLevel(CommentRowsBeans.get(position).getScore(), holder.level);
            holder.content.setText(CommentRowsBeans.get(position).getContent());
            holder.reply.setVisibility(View.GONE);
            holder.likeLL.setVisibility(View.VISIBLE);
            holder.likeNum.setText(String.valueOf(CommentRowsBeans.get(position).getLikeNum()));
            final boolean[] isLike = {false};
            holder.likeLL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!isLike[0]) {
                        new Thread(() -> {
                            String post = Tools.Post("/prod-api/api/movie/film/comment/like/" + CommentRowsBeans.get(position).getId(), MainActivity.sp.getString("token", ""), "");
                            try {
                                JSONObject jx = new JSONObject(post);
                                String msg = jx.getString("msg");
                                int code = jx.getInt("code");
                                runOnUiThread(() -> {
                                    Toast.makeText(MovieInfoAt.this, msg, Toast.LENGTH_SHORT).show();
                                    if (code == 200) {
                                        holder.likeImg.setImageResource(R.drawable.ic_baseline_favorite_24);
                                        holder.likeNum.setText(String.valueOf(CommentRowsBeans.get(position).getLikeNum() + 1));
                                        isLike[0] = true;
                                    }
                                });
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }).start();
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return CommentRowsBeans.size();
        }

        class PlListViewHolder extends RecyclerView.ViewHolder {
            ImageView head;
            TextView name;
            TextView date;
            RatingBar score;
            TextView level;
            TextView content;
            CardView reply;
            TextView replyTime;
            TextView replyContent;
            LinearLayout likeLL;
            ImageView likeImg;
            TextView likeNum;


            public PlListViewHolder(@NonNull View itemView) {
                super(itemView);
                head = itemView.findViewById(R.id.head);
                name = itemView.findViewById(R.id.name);
                date = itemView.findViewById(R.id.date);
                score = itemView.findViewById(R.id.score);
                level = itemView.findViewById(R.id.level);
                content = itemView.findViewById(R.id.content);
                reply = itemView.findViewById(R.id.reply);
                replyTime = itemView.findViewById(R.id.replyTime);
                replyContent = itemView.findViewById(R.id.replyContent);
                likeLL = itemView.findViewById(R.id.likeLL);
                likeImg = itemView.findViewById(R.id.likeImg);
                likeNum = itemView.findViewById(R.id.likeNum);
            }
        }
    }
}